package com.ebt.m.presenter;

import android.content.Context;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.commons.buscomponent.listview.BaseListPresenter;
import com.ebt.m.data.bean.Brand;
import com.ebt.m.data.entity.NewProductInfo;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.data.rxModel.apibean.ProductSearchBean;
import com.ebt.m.data.rxModel.apibean.ProductSearchCategory;
import com.ebt.m.data.rxModel.apibean.SearchHistory;
import com.ebt.m.commons.buscomponent.listview.RecyclerFootManger;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.commons.buscomponent.listview.SectionItem;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by andy.wang on 2016/12/14.
 */

public class ProductSearchPresenter extends BaseListPresenter<IProductSerachListView> {

    private int currentPage = 1;
    private ProductSearchBean searchBean;
    private boolean isFirsthRecommond = false;
    private boolean isRecommond = false;

    public ProductSearchPresenter(Context context, IProductSerachListView iView) {
        super(context, iView);
    }

    @Override
    public void loadNew(Object... args) {
        currentPage = 1;
        isFirsthRecommond = false;
        EBTAPI searchAPI = AppInitService.getEbtApi();
        // 传进来两种参数，Brand 按品牌搜索；ProductSearchBean 按关键词搜索
        Observable.just(args)
                .flatMap(arg -> {
                    if (arg != null && arg.length > 0 && arg[0] instanceof Brand) {//按品牌名称搜索
                        return Observable.just(generaterSelectionParams((Brand) arg[0]));
                    } else if (arg != null && arg.length > 0 && arg[0] instanceof ProductSearchBean) {//按关键词搜索
                        return Observable.just(arg[0]);
                    } else if ((arg == null || arg.length < 1) && searchBean != null) {
                        return Observable.just(searchBean);
                    } else {
                        //首页进入默认搜索
                        //有搜索历史，直接查寻第一个品牌
                        //没有搜索历史，加入推荐产品，如果推荐产品为空，查寻全部品牌的第一个
                        return searchAPI.getSearchHistorys(2, 1, 1, 3)
                                .flatMap(listBaseDataResult -> {
                                    List<SearchHistory> list = listBaseDataResult.getData();
                                    if (list != null && list.size() > 0) {
                                        Brand brand = new Brand();
                                        brand.setBrandId(Integer.valueOf(list.get(0).getSearchId()));
                                        brand.setBrandShortName(list.get(0).getKeyword());
                                        return Observable.just(generaterSelectionParams(brand));
                                    } else {
                                        isFirsthRecommond = true;
                                        Brand brand = new Brand();
                                        brand.setBrandId(ConfigData.RECOMMEND_BRAND_ID);
                                        brand.setBrandShortName("推荐产品");
                                        brand.setBrandName("推荐产品");
                                        return Observable.just(generaterSelectionParams(brand));
                                    }
                                }).onErrorReturn(throwable -> {
                                    Brand brand = new Brand();
                                    brand.setBrandId(ConfigData.RECOMMEND_BRAND_ID);
                                    brand.setBrandShortName("推荐产品");
                                    brand.setBrandName("推荐产品");
                                    return generaterSelectionParams(brand);
                                });

                    }
                })
                .flatMap(search -> {
                    this.searchBean = (ProductSearchBean) search;
                    ProductSearchCategory category = searchBean.getCategory();
                    if (category != null && category.getBrandList() != null && category.getBrandList().size() > 0)
                        iView.updateSearchLabel(category.getBrandList().get(0));
                    return getSearchProducts(searchAPI, currentPage, ConfigData.PAGE_COUNT_LIMIT, searchBean);
                })
                .flatMap(newProductInfos -> {
                    if (newProductInfos == null || newProductInfos.size() == 0) {
                        if (isFirsthRecommond) {
                            isFirsthRecommond = false;
                            return searchAPI.getBrandsByCompanyId(AppContext.getCurrentUser().getCompanyInfo().getCompanyID())
                                    .map(searchCategorys -> {
                                        List<Brand> data = searchCategorys.getData();
                                        return generaterSelectionParams(data.get(0));
                                    })
                                    .flatMap(search -> {
                                        this.searchBean = (ProductSearchBean) search;
                                        ProductSearchCategory category = searchBean.getCategory();
                                        if (category != null && category.getBrandList() != null && category.getBrandList().size() > 0)
                                            iView.updateSearchLabel(category.getBrandList().get(0));
                                        return getSearchProducts(searchAPI, currentPage, ConfigData.PAGE_COUNT_LIMIT, searchBean);
                                    });
                        }
                    }
                    return Observable.just(newProductInfos);
                })
                .filter(getFilterForFootviewStatus(true))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    iView.updateData(createSectionItem(response));
                }, throwable -> {
                    throwable.printStackTrace();
                    iView.errorData();
                });

    }

    private ProductSearchBean generaterSelectionParams(Brand brand) {
        ProductSearchBean searchBean = new ProductSearchBean();
        searchBean.setKeyword("");
        searchBean.setCompanyId(AppContext.getCurrentUser().getCompanyInfo().getCompanyID());
        ProductSearchCategory category = new ProductSearchCategory();
        List<Brand> brandLists = new ArrayList<>();
        brandLists.add(brand);
        category.setBrandList(brandLists);
        searchBean.setCategory(category);
        searchBean.setRequestFrom(2);
        return searchBean;
    }

    @Override
    public void refresh() {
        loadNew(searchBean);
    }

    @Override
    public void loadNext(Object... args) {
        EBTAPI searchApi = AppInitService.getEbtApi();
        getSearchProducts(searchApi, currentPage + 1, ConfigData.PAGE_COUNT_LIMIT, searchBean)
                .filter(getFilterForFootviewStatus(false))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    currentPage++;
                    iView.updateDataAdd(createSectionItem(response));
                }, throwable -> {
                    throwable.printStackTrace();
                    iView.setFootStatus(RecyclerFootManger.STATUS_ERROR, true);
                });
    }

    private Observable<List<NewProductInfo>> getSearchProducts(EBTAPI searchApi, int page, int limitCount, ProductSearchBean searchBean) {
        isRecommond = false;
        ProductSearchCategory category = searchBean.getCategory();
        //是否按品牌搜索
        if (category != null && category.getBrandList() != null && category.getBrandList().size() > 0) {
            Brand brand = category.getBrandList().get(0);
            //是否为推荐品牌
            if (brand.getBrandId() == ConfigData.RECOMMEND_BRAND_ID) {
                isRecommond = true;
                return searchApi.getRecommondProducts(page, limitCount)
                        .map(listBaseDataResult -> listBaseDataResult.getData());

            } else {
                //常规按品牌搜索
                return searchApi.getSearchProducts(page, limitCount, searchBean)
                        .map(productSearchResultBaseDataResult -> productSearchResultBaseDataResult.getData().getItems());
            }
        } else {
            return searchApi.getSearchProducts(page, limitCount, searchBean)
                    .map(productSearchResultBaseDataResult -> productSearchResultBaseDataResult.getData().getItems());
        }
    }

    public List<SectionItem> createSectionItem(List list) {
        List<SectionItem> sections = new ArrayList<SectionItem>();
        if (list == null || list.size() < 1) {
            return sections;
        }
        try {
            for (int i = 0; i < list.size(); i++) {
                NewProductInfo productInfo = (NewProductInfo) list.get(i);
                SectionItem item = new SectionItem(0, productInfo);
                item.extras = isRecommond;
                sections.add(item);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return sections;
        }
        return sections;
    }

    protected Predicate<List<NewProductInfo>> getFilterForFootviewStatus(boolean isLoadNew) {
        return data -> {
            if (data == null || data.size() == 0) {
                if (!isLoadNew) {
                    iView.setFootStatus(RecyclerFootManger.STATUS_END, true);
                    return false;
                } else {
                    iView.setFootStatus(RecyclerFootManger.STATUS_NORMAL, true);
                    return true;
                }
            }

            if (data.size() < ConfigData.PAGE_COUNT_LIMIT) {
                iView.setFootStatus(RecyclerFootManger.STATUS_END, true);
                return true;
            } else {
                iView.setFootStatus(RecyclerFootManger.STATUS_LOADING, true);
                return true;
            }
        };
    }
}
